<template>
  <div class="timeline-container">
    <div class="timeline-content">
      <!-- 左边播放控制和日期选择 -->
      <div class="controls">
        <!-- <button @click="togglePlayPause">
          {{ isPlaying ? "暂停" : "播放" }}
        </button> -->
        <input
          type="date"
          v-model="selectedDate"
          @change="handleDateChange"
          class="date-picker"
          :min="minDate"
        />
      </div>

      <!-- 右边时间轴 -->
      <div class="timeline-r">
        <!-- 进度条 -->
        <div class="progress-bar-background">
          <div class="progress-bar" :style="{ width: progress + '%' }"></div>
        </div>

        <div class="timeline">
          <div
            class="day"
            v-for="(day, index) in timeline"
            :key="index"
            :style="{ width: 100 / 7 + '%' }"
          >
            <!-- 每天的小时 -->
            <div class="hours">
              <div
                v-for="(time, timeIndex) in day.times"
                :key="timeIndex"
                class="time-point"
                :class="{
                  active: isCurrentTime(time.timestamp),
                  highlighted: isHighlighted(time.timestamp),
                }"
                @click="onTimeClick(time.timestamp, index, timeIndex)"
              >
                <!-- 小竖线刻度在上方 -->
                <div class="hour-line"></div>
                {{ time.time }}
                <!-- 显示小时 -->
              </div>
            </div>

            <!-- 每个日期的日期 -->
            <div class="date">{{ formatDisplayDate(day.date) }}</div>

            <!-- 每个日期的大竖线分隔，显示在最后一个时间段的右边 -->
            <div class="day-divider" v-if="index < timeline.length - 1"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onBeforeUnmount } from "vue";
import eventBus from "@/utils/eventBus"; // 导入事件总线

// 定义 props
const props = defineProps({
  isForecastShow: {
    type: Boolean,
    required: false,
    default: false,
  },
});

// 定义响应式数据
const currentIndex = ref(0); // 当前播放的索引
const timeline = ref([]); // 时间轴数据
const isPlaying = ref(false); // 是否正在播放
const timer = ref(null); // 定时器
const progress = ref(0); // 播放进度（0 - 100）
const highlightedIndex = ref(null); // 存储当前被点击高亮的时间段索引
const selectedDate = ref("2025-03-19"); // 保持默认值不变
const minDate = "2022-01-01"; // 最小允许选择的日期

// 在时间变化的地方触发事件
const emitTimeChange = () => {
  const currentSegment = getCurrentSegment();
  if (currentSegment) {
    eventBus.setSelectedDate(new Date(currentSegment.timestamp));
  }
};

// 初始化时间轴
function initTimeline() {
  timeline.value = generateTimeline(selectedDate.value);
}

// 生成时间轴数据
function generateTimeline(startDate) {
  const days = [];
  const currentDate = new Date(startDate);
  for (let i = 0; i < 7; i++) {
    const date = new Date(currentDate);
    date.setDate(date.getDate() + i);
    const dateString = date.toISOString().split("T")[0]; // 获取格式化日期
    days.push({
      date: dateString,
      times: generateTimesForDay(date),
    });
  }
  return days;
}

// 生成每天的时间段
function generateTimesForDay(date) {
  const times = [];
  const hours = [0, 3, 9, 12, 15, 18, 21]; // 设定每一天的时间段
  hours.forEach((hour) => {
    const time = `${hour}`; // 不显示:00，只显示小时数
    const timestamp = new Date(date).setHours(hour, 0, 0, 0); // 设置时间戳
    times.push({
      time: time,
      timestamp: timestamp,
    });
  });
  return times;
}

// 格式化显示日期 (MM-DD)
function formatDisplayDate(dateString) {
  const date = new Date(dateString);
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${month}-${day}`;
}

// 处理日期变化
function handleDateChange() {
  const selected = new Date(selectedDate.value);
  const minAllowed = new Date(minDate);

  // 验证日期是否合法
  if (selected < minAllowed) {
    selectedDate.value = minDate; // 自动重置为最小允许日期
    return;
  }

  pause();
  currentIndex.value = 0;
  progress.value = 0;
  highlightedIndex.value = null;
  initTimeline();
  emitTimeChange();
  if (props.isForecastShow) {
    play();
  }
}

// 判断是否是当前时间段
function isCurrentTime(timestamp) {
  const currentSegment = getCurrentSegment();
  return currentSegment && currentSegment.timestamp === timestamp;
}

// 判断是否是高亮时间段
function isHighlighted(timestamp) {
  return (
    highlightedIndex.value !== null &&
    timeline.value[highlightedIndex.value.dayIndex].times[
      highlightedIndex.value.timeIndex
    ].timestamp === timestamp
  );
}

// 获取当前时间段
function getCurrentSegment() {
  const totalSegments = timeline.value.length * 8;
  if (currentIndex.value < totalSegments) {
    const dayIndex = Math.floor(currentIndex.value / 8);
    const timeIndex = currentIndex.value % 8;
    return timeline.value[dayIndex].times[timeIndex];
  }
  return null;
}

// 播放时间轴
function play() {
  isPlaying.value = true;
  timer.value = setInterval(() => {
    currentIndex.value++;
    emitTimeChange();
    updateProgress();
    // 如果到达最后一个时间段，重置并循环播放
    if (currentIndex.value >= timeline.value.length * 8) {
      currentIndex.value = 0;
      updateProgress();
    }
  }, 1000); // 每秒自动播放一次
}

// 更新进度条
function updateProgress() {
  const totalSegments = timeline.value.length * 8; // 总时间段数
  progress.value = (currentIndex.value / totalSegments) * 100 + 1; // 进度百分比
}

// 暂停时间轴
function pause() {
  isPlaying.value = false;
  clearInterval(timer.value);
}

// 点击某个小时段时的处理
function onTimeClick(timestamp, dayIndex, timeIndex) {
  highlightedIndex.value = { dayIndex, timeIndex }; // 设置高亮索引
  currentIndex.value = dayIndex * 8 + timeIndex; // 更新当前索引
  updateProgress(); // 更新进度条
  pause(); // 点击时暂停播放
  emitTimeChange();
}

// 监听 isForecastShow 变化
watch(
  () => props.isForecastShow,
  (newVal) => {
    if (newVal) {
      currentIndex.value = 0;
      progress.value = 0;
      play();
    } else {
      if (timer.value) {
        clearInterval(timer.value); // 清除定时器
      }
    }
  },
  { deep: true }
);

// 初始化时间轴
initTimeline();

// 组件销毁前清除定时器
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style scoped>
/* 容器样式 */
.timeline-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 5%;
  background-color: rgba(255, 255, 255, 0.8); /* 半透明背景 */
  backdrop-filter: blur(5px); /* 背景模糊效果 */
  z-index: 1000; /* 确保在最上层 */
  display: flex;
  align-items: center;
}

/* 背景进度条 */
.progress-bar-background {
  width: 100%;
  height: 4px; /* 减小进度条高度 */
  background-color: #e0e0e0;
  border-radius: 2px;
  box-sizing: border-box;
}

.progress-bar {
  height: 100%;
  background-color: #209e86;
  border-radius: 2px;
  transition: width 0.1s ease-in-out;
}

.timeline-content {
  width: 100%;
  height: 100%;
  display: flex;
}

.timeline-r {
  width: 90%;
}

/* 时间轴样式 */
.timeline {
  display: flex;
  width: 100%;
  overflow-x: auto;
  box-sizing: border-box;
}

/* 播放控制按钮 */
.controls {
  width: 10%;
  display: flex;
  align-items: center;
  padding-left: 6px;
  gap: 5px;
}

.date-picker {
  padding: 2px;
  border: 1px solid #ccc;
  border-radius: 3px;
  font-size: 10px;
  width: 100px;
}

.day {
  display: inline-block;
  text-align: center;
  position: relative;
  width: calc(100% / 7);
  box-sizing: border-box;
  padding-bottom: 2px; /* 减小内边距 */
}

.hours {
  display: flex;
  justify-content: space-between;
  position: relative;
  margin-top: 2px; /* 减小外边距 */
  box-sizing: border-box;
}

.time-point {
  position: relative;
  cursor: pointer;
  text-align: center;
  font-size: 10px; /* 减小字体大小 */
  border-radius: 50%;
  width: 20px; /* 减小宽度 */
  height: 20px; /* 减小高度 */
  line-height: 20px; /* 调整行高 */
}

.time-point.active {
  background-color: #209e86;
  color: white;
  font-weight: bold;
}

/* 高亮显示 */
.time-point.highlighted {
  background-color: #209e86;
  color: white;
  font-weight: bold;
}

/* 小竖线刻度现在位于上方 */
.hour-line {
  position: absolute;
  top: -8px; /* 调整位置 */
  left: 50%;
  transform: translateX(-50%);
  width: 1px; /* 减小宽度 */
  height: 8px; /* 减小高度 */
  background-color: #f5d5d5;
}

/* 日期 */
.date {
  font-weight: bold;
  font-size: 10px; /* 减小字体大小 */
  margin-top: 2px; /* 减小外边距 */
  white-space: nowrap; /* 防止日期换行 */
}

/* 大竖线分隔出现在每个日期的右边 */
.day-divider {
  position: absolute;
  top: 0;
  right: 0;
  width: 2px; /* 减小宽度 */
  height: 100%;
  background-color: #00ffff;
}

button {
  padding: 4px 8px; /* 减小内边距 */
  background-color: #0d213c;
  opacity: 0.9;
  color: white;
  border: none;
  border-radius: 3px; /* 减小圆角 */
  cursor: pointer;
  font-size: 10px; /* 减小字体大小 */
}

button:hover {
  background-color: #0d213c;
}
.controls {
  width: 12%;
  display: flex;
  align-items: center;
  padding-left: 10px;
  gap: 8px;
}

.date-picker-container {
  position: relative;
  display: inline-block;
}

.date-picker {
  padding: 4px 8px 4px 28px;
  border: 1px solid rgba(13, 33, 60, 0.3);
  border-radius: 4px;
  font-size: 12px;
  width: 110px;
  height: 28px;
  background-color: rgba(255, 255, 255, 0.9);
  color: #0d213c;
  cursor: pointer;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.date-picker:hover {
  border-color: rgba(13, 33, 60, 0.5);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.15);
}

.date-picker:focus {
  outline: none;
  border-color: #209e86;
  box-shadow: 0 0 0 2px rgba(32, 158, 134, 0.2);
}

.calendar-icon {
  position: absolute;
  left: 8px;
  top: 50%;
  transform: translateY(-50%);
  color: #209e86;
  pointer-events: none;
}

/* 针对不同浏览器的日期选择器样式 */
.date-picker::-webkit-calendar-picker-indicator {
  opacity: 0;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.date-picker::-webkit-datetime-edit {
  padding: 0;
}

.date-picker::-webkit-datetime-edit-fields-wrapper {
  color: #0d213c;
}
</style>
